<template>
  <div class="generate-qa">
    <el-card>
      <template #header>
        <h2 class="title">问卷发布链接</h2>
      </template>

      <div class="questionnaire-info">
        <p>问卷标题：{{ title }}</p>
        <p>问卷描述：{{ description }}</p>
      </div>

      <el-divider />

      <!-- 显示问卷链接 -->
      <div class="link-section" v-if="isLinkValid">
        <h3>填写问卷链接：</h3>
        <el-input
          v-model="questionnaireLink"
          type="text"
          readonly
          class="link-input"
          :placeholder="'点击下方按钮复制链接'"
        >
          <template #append>
            <el-button @click="copyLink" icon="el-icon-copy-document" size="small">
              复制链接
            </el-button>
          </template>
        </el-input>
      </div>

      <div v-else>
        <el-alert title="问卷已停止发布或尚未开始，无法填写" type="error" />
      </div>

      <el-divider />

      <!-- 显示二维码 -->
      <div class="qr-section" v-if="isLinkValid">
        <h3>扫描二维码填写问卷：</h3>
        <div v-if="qrCodeUrl" class="qr-code">
          <img :src="qrCodeUrl" alt="二维码" />
        </div>
      </div>

      <!-- 停止发布按钮 -->
      <div class="actions" v-if="questionnaire.status === '1'">
        <el-button type="danger" @click="confirmStopPublish">停止发布</el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
      <div class="actions" v-else>
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage,ElMessageBox } from 'element-plus'
import QRCode from 'qrcode'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()

const qid = route.params.id
const startTime = route.query.startTime
const endTime = route.query.endTime
const title = route.query.title || '未知问卷'
const description = route.query.description || '暂无描述'
const questionnaireLink = ref('')
const qrCodeUrl = ref('')
const isLinkValid = ref(true)
const questionnaire = ref({
  id: qid,
  status: route.query.status || '0'  // 0: 未发布, 1: 已发布
})

// ✅ 改成前端地址（关键）192.168.0.195
const LAN_IP = '192.168.0.195'
const PORT = 81
const baseUrl = `http://${LAN_IP}:${PORT}/WriteAnswer`
//const baseUrl = `http://localhost:${PORT}/WriteAnswer`

const generateQRCode = async () => {
  const formattedDate = dayjs(endTime).format('YYYY-MM-DD HH:mm:ss');
  const link = 
  `${baseUrl}/${qid}?title=${encodeURIComponent(title)}&description=${encodeURIComponent(description)}&endTime=${encodeURIComponent(formattedDate)}`
  questionnaireLink.value = link

  try {
    qrCodeUrl.value = await QRCode.toDataURL(link)
  } catch (err) {
    ElMessage.error('生成二维码失败')
    console.error(err)
  }
}

const copyLink = () => {
  if (!questionnaireLink.value) return
  navigator.clipboard.writeText(questionnaireLink.value)
  ElMessage.success('链接已复制到剪贴板')
}

const goBack = () => {
  router.push(`/HomePage/QuestionnaireList`)
}

const confirmStopPublish = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要停止发布该问卷吗？停止发布后问卷将不再可填写。',
      '停止发布确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    handleStopPublish()
  } catch {
    ElMessage.info('已取消停止发布')
  }
}

// 真正执行停止发布请求
const handleStopPublish = async () => {
  const params = {
    id: questionnaire.value.id,
    status: '0',
    endTime: dayjs().format('YYYY-MM-DD HH:mm:ss')  // 当前时间作为结束时间
  }
  // console.log('params',params)

  try {
    const res = await request.post('/questionnaire/updateQuestionnaire', params)
    if (res.status === 200) {
      ElMessage.success('问卷已停止发布')
      questionnaire.value.status = '0'  // 更新状态为“未发布”
      isLinkValid.value = false // 禁用问卷填写链接
    } else {
      ElMessage.error('停止发布失败')
    }
  } catch (err) {
    console.log('请求出错:', err)
    ElMessage.error('停止发布失败')
  }
}

onMounted(() => {
  // 判断问卷是否在有效期内
  const currentDate = new Date()

  if (currentDate < new Date(startTime) || currentDate > new Date(endTime)) {
    isLinkValid.value = false
  }

  generateQRCode()
})
</script>

<style scoped>
.generate-qa {
  padding: 30px;
  background-color: #fff;
}

.title {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
}

.questionnaire-info {
  text-align: center;
  margin-bottom: 20px;
}

.link-section {
  margin: 20px 0;
}

.link-input {
  width: 100%;
}

.qr-section {
  text-align: center;
  margin-top: 20px;
}

.qr-code {
  display: inline-block;
  margin: 20px auto;
  width: 180px;
  height: 180px;
}

.actions {
  text-align: center;
  margin-top: 30px;
}
</style>
